package client;

import java.io.*;
import java.net.Socket;
import java.util.AbstractMap;

import com.google.gson.Gson;
import model.*;

// 此类用来获取服务端发送给客户端的数据
public class MessageReceiver implements Runnable{
	private DataInputStream dis;
	private boolean flag=true;
	private StreamCloser s;
	
	//构造函数
	public MessageReceiver(Socket client)
	{
		try
		{
			dis = new DataInputStream(client.getInputStream());
		}catch (IOException e)
		{
			flag = false;
			e.printStackTrace();
			s.closeall(client,dis);
		}
	}
	
	private String Receive()
	{
		try
		{
			Gson gson = new Gson();
			String json = dis.readUTF();
			Message mes = gson.fromJson(json, Message.class);
			if(mes.getType() == MsgType.COMMON_MESSAGE) {
				return mes.getText();
			}
			return null;
		}catch (IOException e)
		{
			flag = false;
			e.printStackTrace();
			s.closeall(dis);
			return null;
		}
	}
	
	public void run()
	{
		while(flag)
		{
			System.out.println(this.Receive());
		}
	}
	
	public class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {
        public Pair(K key, V value) {
            super(key, value);
        }
    }
}
